package com.fy.oa.zc.crm;

import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
//import java.io.BufferedReader;
//import java.io.InputStream;
//import java.io.InputStreamReader;
//import java.io.OutputStream;
//import java.net.HttpURLConnection;
//import java.net.URL;
import java.util.Map;
import java.util.Set;

import javax.xml.rpc.ServiceException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.fy.oa.zc.domain.FySummaryView;
import com.fy.oa.zc.exception.FyOAException;
import com.fy.oa.zc.manager.AFyOA_FormEventManager;
import com.fy.oa.zc.manager.FyOA_FormEventManager;
import com.fy.oa.zc.plm.webservice.client.ComPlmOaBeanNewProjectReportInfo;
import com.fy.oa.zc.plm.webservice.client.ComPlmOaBeanProcessingResult;
import com.fy.oa.zc.plm.webservice.client.FyplmNewProjectReportService;
import com.fy.oa.zc.plm.webservice.client.FyplmNewProjectReportServiceService;
import com.fy.oa.zc.plm.webservice.client.FyplmNewProjectReportServiceServiceLocator;
import com.fy.oa.zc.soap.client.FyOA_SOAPClient;

public class FyOA2CRM_NewProductPoject_ManagerImpl extends AFyOA_FormEventManager implements FyOA_FormEventManager {

	private String soapServicePath="http://10.111.0.162:7777";

	public void setSoapServicePath(String soapServicePath) {
		this.soapServicePath = soapServicePath;
	}

	public String toString() {
		return "新产品立项";
	}

	private void resultParse(String xml) {
		try {
			Document doc = DocumentHelper.parseText(xml);
			doc.getRootElement().addNamespace("siebelf", "http://www.siebel.com/ws/fault");
			doc.getRootElement().addNamespace("ns", "http://siebel.com/CustomUI");
			List<?> list = doc.selectNodes("//ns:ResultInfo");
			if (list.size() == 1) {
				Element node = (Element) list.get(0);
				String msg = node.getText();
				if (msg != null && !"".equals(msg)) {
					throw new FyOAException("新产品立项信息写入CRM失败，错误提示为：" + msg);
				}
			} else if (list.size() == 0) {
				list = doc.selectNodes("//siebelf:errormsg");
				if (list.size() == 1) {
					throw new FyOAException("新产品立项信息写入CRM失败，错误提示为：" + ((Element) list.get(0)).getText());
				}
				throw new FyOAException("新产品立项信息写入CRM失败，未知的错误！");
			} else {
				throw new FyOAException("新产品立项接口返回XML数据异常，出现多个ErrorMessage");
			}
		} catch (DocumentException e) {
			throw new FyOAException("解析新产品立项接口返回XML数据发生异常", e);
		}
	}

	private String createSendXML(Map<String, String> values, String state) {
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(SENDXMLTEMPLATE);
		} catch (DocumentException e) {
			throw new FyOAException("解析XML模板失败", e);
		}
		((Element) doc.selectNodes("//proj:Receive_Input//proj:Comments").get(0)).setText((String) values.get("批准人意见"));
		((Element) doc.selectNodes("//proj:Receive_Input//proj:Status").get(0)).setText(state);
		((Element) doc.selectNodes("//proj:Receive_Input//proj:PartNumId").get(0))
				.setText((String) values.get("零件号行ID"));
		((Element) doc.selectNodes("//proj:Receive_Input//proj:OptyCode").get(0)).setText((String) values.get("项目号"));

		return doc.asXML();
	}

	@Override
	public String dealFinishEvent(FySummaryView view, long affairid) {

		Map<String, String> values = super.fyOARestClient.getFormValues(view.getSummaryid(), this.formNameSet_PLM);
		try {
			resultParse(fyOA_SOAPClient.post(createSendXML(values, "生效"),
					soapServicePath + "/eai_anon_chs/start.swe?SWEExtSource=SecureWebService&SWEExtCmd=Execute",
					"\"document/http://siebel.com/Opportunity/ProjectApplication:Receive\""));
		} finally {
			try {
				post_plm(values);
			} catch (RemoteException e) {
				throw new FyOAException("访问PLM接口发生异常，异常单据summaryid:" + view.getSummaryid(), e);
			} catch (ServiceException e) {
				throw new FyOAException("访问PLM接口发生异常，异常单据summaryid:" + view.getSummaryid(), e);
			} catch (Exception e) {
				throw new FyOAException("访问PLM接口发生异常，异常单据summaryid:" + view.getSummaryid(), e);
			}
		}
		return view.toString();
	}

	@Override
	public String dealStopEvent(FySummaryView view) {
		Map<String, String> values = getValues(view.getSummaryid());
		resultParse(fyOA_SOAPClient.post(createSendXML(values, "拒绝"),
				soapServicePath + "/eai_anon_chs/start.swe?SWEExtSource=SecureWebService&SWEExtCmd=Execute",
				"\"document/http://siebel.com/Opportunity/ProjectApplication:Receive\""));
		return view.toString();
	}

	@Override
	public String dealCancelEvent(FySummaryView view, long userid, String message) {
		Map<String, String> values = getValues(view.getSummaryid());
		resultParse(fyOA_SOAPClient.post(createSendXML(values, "拒绝"),
				soapServicePath + "/eai_anon_chs/start.swe?SWEExtSource=SecureWebService&SWEExtCmd=Execute",
				"\"document/http://siebel.com/Opportunity/ProjectApplication:Receive\""));
		return view.toString();
	}

//	private void printLog(String title,String msg){
//		logger.info(title + ">>>>>>>>>>>>" + msg);
//		System.out.println(title + ">>>>>>>>>>>>" + msg);
//	}
	private void post_plm(Map<String, String> values) throws ServiceException, RemoteException {

		logger.info("导入新产品立项数据<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
		System.out.println("导入新产品立项数据<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
		
//		printLog()
//		values.get("车型名称"), getNowTime(), values.get("客户名称"), values.get("客户生产地点"), values.get("项目号"),
//		values.get("量产时间"), values.get("生产事业部"), values.get("供货比例"), values.get("停产时间"), values.get("总供货产量");
		ComPlmOaBeanNewProjectReportInfo info = new ComPlmOaBeanNewProjectReportInfo(values.get("项目号").substring(0, 12),
				values.get("车型名称"), getNowTime(), values.get("客户名称"), values.get("客户生产地点"), values.get("项目号"),
				values.get("产量时间"), values.get("生产事业部"), values.get("供货比例"), values.get("停产时间"), values.get("总供货产量"));
		FyplmNewProjectReportServiceService fnprss = new FyplmNewProjectReportServiceServiceLocator();
		FyplmNewProjectReportService fnprs = fnprss.getComFyOaFyplmNewProjectReportService();
		ComPlmOaBeanProcessingResult[] result = fnprs.getNPReport("Test Everything", "1",
				new ComPlmOaBeanNewProjectReportInfo[] { info });
		if (result != null && result[0].getMessageText() != null&& !"".equals(result[0].getMessageText())) {
			throw new FyOAException("新产品立项数据写入PLM失败，错误提示：" + result[0].getMessageText());
		}
		logger.info("新产品立项数据写入PLM成功》》》》》》》》》》》》》》》");
		System.out.println("新产品立项数据写入PLM成功》》》》》》》》》》》》》》》");
	}

	public String getNowTime() {
		java.util.Date date = Calendar.getInstance().getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(date);
	}

	public void setFyOA_SOAPClient(FyOA_SOAPClient fyOA_SOAPClient) {
		this.fyOA_SOAPClient = fyOA_SOAPClient;
	}

	public void setFormNameSet_PLM(Set<String> formNameSet_PLM) {
		this.formNameSet_PLM = formNameSet_PLM;
	}

	private FyOA_SOAPClient fyOA_SOAPClient;
	private Set<String> formNameSet_PLM;
	private static final Log logger = LogFactory.getLog(FyOA2CRM_NewProductPoject_ManagerImpl.class);

	private static final String SENDXMLTEMPLATE = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"\n"
			+ "	xmlns:proj=\"http://siebel.com/Opportunity/ProjectApplication\">\n" + "	<soapenv:Header>\n"
			+ "		<wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/07/secext\">\n"
			+ "			<wsse:UsernameToken xmlns:wsu=\"http://schemas.xmlsoap.org/ws/2002/07/utility\">\n"
			+ "				<wsse:Username>GUESTERM</wsse:Username>\n"
			+ "				<wsse:Password Type=\"wsse:PasswordText\">GUESTERM</wsse:Password>\n"
			+ "			</wsse:UsernameToken>\n" + "		</wsse:Security>\n" + "	</soapenv:Header>\n"
			+ "	<soapenv:Body>\n" + "		<proj:Receive_Input>\n" + "			<proj:Comments></proj:Comments>\n"
			+ "			<proj:Status></proj:Status>\n" + "			<proj:PartNumId></proj:PartNumId>\n"
			+ "			<proj:OptyCode></proj:OptyCode>\n" + "		</proj:Receive_Input>\n" + "	</soapenv:Body>\n"
			+ "</soapenv:Envelope>";

}
